<?php

// returns array $a, $a[i] -- $result
// $result['note_id']
// $result['edit_id']
// $result['line_number']
// $result['line']
function search($user, $query) {
    global $data_dir;
    // TODO: something with double quotes
    $grep = array();
    exec("grep -Rin ".escapeshellarg($query)." ".$data_dir.$user['id'], $grep);
    $answer = array();
    foreach ($grep as $s) {
        $n = strlen($s);
        $i = 0;
        while ($i < $n && $s[$i] != '/' && $s[$i] != "\\") $i++;
        while ($i < $n && $s[$i] != ':') $i++;
        $filename = substr($s, 0, $i);
        $edit_id = basename($filename);
        $note_id = basename(substr($s, 0, $i - strlen($edit_id)));
        $i++;
        $j = $i;
        while ($j < $n && $s[$j] != ':') $j++;
        $line_number = substr($s, $i, $j - $i);
        $line = substr($s, $j + 1);
        
        if (!isset($answer[$note_id])) {
            $answer[$note_id] = array($edit_id => array($line_number => $line));
        } else if (!isset($answer[$note_id][$edit_id])) {
            $answer[$note_id][$edit_id] = array($line_number => $line);
        } else {
            $answer[$note_id][$edit_id][$line_number] = $line;
        }
    }
    return $answer;
}

?>
